from rest_framework import serializers
from apps.nav.models import NavModel


class NavModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = NavModel
        exclude = ["create_time", "update_time"]

        extra_kwargs = {
            "name": {
                "min_length": 2,
                "max_length": 30,
                "error_messages": {
                    "min_length": "导航栏名称长度为 2-30 个字符！",
                    "max_length": "导航栏名称长度为 2-30 个字符！"
                }
            },
            "icon": {
                "min_length": 2,
                "max_length": 50,
                "error_messages": {
                    "min_length": "导航栏图标长度为 2-50 个字符！",
                    "max_length": "导航栏图标长度为 2-50 个字符！"
                }
            },
            "path": {
                "min_length": 2,
                "max_length": 50,
                "error_messages": {
                    "min_length": "导航栏路径长度为 2-50 个字符！",
                    "max_length": "导航栏路径长度为 2-50 个字符！"
                }
            },
            "pid": {
                "required": False
            }
        }

    def validate_pid(self, value):
        """判断上级导航栏是否存在"""
        if value != 0 and not NavModel.objects.filter(id=value):
            raise serializers.ValidationError("上级导航栏不存在！")
        return value

